"""在屏幕中识别指定图片，并返回坐标"""
from pathlib import Path
import sys
project_root = Path(__file__).parent.parent
sys.path.append(str(project_root))
import cv2
import numpy as np
import pyautogui
from PIL import ImageGrab
import time
from utils.loggerUtils import *

def findImageOnScreen(template_path, confidence=0.8):
    """
    在屏幕上查找指定图片的位置
    :param template_path: 模板图片的路径
    :param confidence: 匹配置信度阈值，默认0.8
    :return: 如果找到，返回目标中心坐标(x, y)；否则返回None
    """
    # 截取屏幕[citation:3][citation:7]
    screenshot = ImageGrab.grab()
    screenshot.save('screenshot.png')
    screenshot = np.array(screenshot)
    # PIL图像转换为BGR格式的OpenCV图像[citation:9]
    screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)

    # 读取模板图片
    template = cv2.imread(template_path)
    if template is None:
        raise FileNotFoundError(f"模板图片未找到：{template_path}")

    # 获取模板图片的尺寸
    h, w = template.shape[:2]

    # 使用模板匹配[citation:10]
    result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

    # 检查匹配度是否超过阈值
    if max_val >= confidence:
        top_left = max_loc
        center_x = top_left[0] + w // 2
        center_y = top_left[1] + h // 2

        # 对于MacBook Retina屏幕，可能需要将坐标除以2[citation:8]
        center_x //= 2
        center_y //= 2

        return center_x, center_y
    else:
        return None

def findAndClick(img,limit_time,confidence=0.8):
    try:
        start_time = int(time.time())
        while int(time.time())-start_time < limit_time:
            coordinates = findImageOnScreen(img, confidence)
            if coordinates:
                x, y = coordinates
                info(f"找到{img}，中心坐标：({x}, {y})")
                pyautogui.click(x, y)
                break
            else:
                info(f"未找到{img},已经寻找了{int(time.time())-start_time}秒,超过{limit_time}秒后进行下一步")

    except FileNotFoundError as e:
        info(e)
    except Exception as e:
        info(f"发生错误：{e}")